import { Modal, Divider, Row, Col, Button, Form, Upload, Icon, message } from 'antd';
import React from 'react';
import { convertParams } from '../../utils/form';

export const ImportForm = Form.create()(props => {
  const { 
    title='导入',
    visible, 
    form, 
    field = 'file',
    onCancel,

    // 下载模板
    onDownload,

    // 导入
    onImport,

    // 其他字段的扩展
    header,
    footer,
  } = props;

  const onOk = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const { file, ...extra } = fieldsValue;

      form.resetFields();

      onImport && onImport({
        file: file[0].originFileObj, // MUST: file 字段！！！！
        ...convertParams(extra)
      });
    });
  };

  const uploadProps = {
    name: 'file',
    // multiple: false,
    beforeUpload: () => false,
    // beforeUpload return false
    // action: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
    onChange (info) {
      const { status } = info.file;

      console.log(info);

      if (status !== 'uploading') {

      }

      if (status === 'done') {
        // message.success(`${info.file.name} 上传成功.`);
      } else if (status === 'error') {
        // message.error(`${info.file.name} 上传失败.`);
      }
    },
  };

  const normFile = e => {
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  };

  return (
    <Modal
      destroyOnClose
      title={title}
      visible={visible}
      onOk={onOk}
      onCancel={() => onCancel()}
      // footer={null}
      footer={[
        <Button key="submit" type="primary" onClick={onOk} style={{ marginRight: 40 }}>
          保存
        </Button>,
        <Button key="back" onClick={() => onCancel()}>
          取消
        </Button>,
      ]}
      width={600}
    >
      { header && header(form) }

      {
        onDownload &&
        <Row>
          <Col span={18}>
            <Button type="primary" onClick={onDownload}>点击下载模板</Button>
          </Col>
        </Row>
      }
      <Divider />

      {/* <FileUploadForm 
        {...props}
      /> */}

      <Form.Item wrapperCol={{ span: 24 }}>
        {form.getFieldDecorator(field, {
          valuePropName: 'fileList',
          getValueFromEvent: normFile,
          rules: [{ required: true, message: '请上传文件！' }],
        })(
          <Upload.Dragger {...uploadProps}>
            <p className="ant-upload-drag-icon">
              <Icon type="inbox" />
            </p>
            <p className="ant-upload-text">点击或拖动文件到此上传</p>
            <p className="ant-upload-hint"></p>
          </Upload.Dragger>,
        )}
      </Form.Item>
    </Modal>
  );
});
